package com.example.dell.intelligentagriculture;


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.dell.intelligentagriculture.utils.MyApp;

public class LoginActivity extends AppCompatActivity {

    EditText etIp;
    Button btnlogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        etIp = findViewById(R.id.et_ip);
        btnlogin = findViewById(R.id.btn_login);
        btnlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String ip = etIp.getText().toString().trim();
                boolean b = matchIp(ip);
                if (b) {
                    //登录页面
                    MyApp myApp = (MyApp) getApplication();
                    myApp.setIp(ip);
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, "IP格式有误", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 192.168.16.2
     * \\d{1,3} 表示1~3 位的数字  1-999
     * \d  \n
     */
    private boolean matchIp(String ip) {
        //正则表达式验证  3333.66.5.99
        boolean matches = ip.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
        boolean b = false;
        if (matches) {
            String[] split = ip.split("\\.");//{ 192  ,  168  , 16  ,2}
            if (Integer.parseInt(split[0]) < 256) {
                if (Integer.parseInt(split[1]) < 256) {
                    if (Integer.parseInt(split[2]) < 256) {
                        if (Integer.parseInt(split[3]) < 256) {
                            b = true;
                        }
                    }
                }
            }
        }
        return b;
    }
}
